package com.ctg.itrdc.mainframe.control;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ctg.itrdc.cache.common.exception.CacheConfigException;
import com.ctg.itrdc.cache.common.utils.PropertiesUtils;
import com.ctg.itrdc.sysmgr.permission.core.CtgUser;
import com.ctg.itrdc.sysmgr.permission.core.IPermissionService;
import com.ctg.itrdc.sysmgr.permission.core.control.CommonResult;
import com.ctg.itrdc.sysmgr.permission.core.utils.WebUtils;
import com.ctg.mainframe.sdk.dto.SysMgrInfoDTO;
import com.ctg.mainframe.sdk.utils.CacheHelper;
import com.ctg.mainframe.sdk.utils.LoginSessionHelper;

@Controller
@RequestMapping("/system_post")
public class SystemPostController {

	private static final String SYS_CODE = "sysCode";
	private static final String SYS_PROPERTIES = "sys.properties";

	@Resource
	private IPermissionService permissionService;

	/**
	 * @api {get} /system_post/query/sysUserId 岗位列表查询
	 * @apiGroup system_post
	 * @apiName selectBySysUserId
	 * @apiDescription 根据系统用户id，获取系统用户对应岗位列表
	 * @apiParam {Long} sysUserId 必传 系统用户id
	 * @apiVersion 0.0.1
	 */
	@RequestMapping("/query/sysUserId")
	@ResponseBody
	public CommonResult selectBySysUserId(@RequestParam(required = false) Long sysUserId) {
		// 从session中获取userId
		// 根据userId通过权限组件查询该用户的岗位列表
		if (sysUserId == null) {
			CtgUser ctgUser = WebUtils.getCtgUser();
			if (ctgUser != null && ctgUser.getSysUserId() != null) {
				sysUserId = ctgUser.getSysUserId();
			}
		}
		List<Map<String, Object>> resultList = permissionService.getPostByUId(sysUserId);

		return new CommonResult(HttpStatus.OK.toString(), "岗位列表查询成功", resultList);
	}

	/**
	 * @throws CacheConfigException
	 * @api {get} /system_post/set/sysPost 岗位列表查询
	 * @apiGroup system_post
	 * @apiName setSystemPost
	 * @apiDescription 登录后，设置岗位。并设置到分布式缓存。
	 * @apiParam {Long} sysPostId 必传 系统岗位id
	 * @apiParam {Long} rzOrgId 必传 任职岗位id
	 * @apiVersion 0.0.1
	 */
	@RequestMapping("/set/sysPostId")
	@ResponseBody
	public CommonResult setSystemPost(
			@RequestParam(required = false) Long sysUserId,
			@RequestParam(required = true) Long sysPostId,
			HttpServletResponse response) throws CacheConfigException {

		Subject subject = SecurityUtils.getSubject();
		if (!subject.isAuthenticated()) {
			throw new AuthenticationException("亲，没登录咧。请登录后访问~");
		}

		// 设置缓存DTO
		SysMgrInfoDTO sysMgrInfo = new SysMgrInfoDTO();
		
		// 设置系统编码
		sysMgrInfo.setSysCode(System.getProperty(SYS_CODE, "ctg-ae"));

		// 从session中获取CtgUser
		CtgUser user = WebUtils.getCtgUser();
		if (sysUserId == null)
			sysUserId = user.getSysUserId();
		

		if (sysPostId != null) {
			// 查询post与user的关系。不存在关系抛异常
			if (!permissionService.existRelation(sysUserId, sysPostId)) { // 走sysPost缓存
				subject.logout();
				throw new AuthenticationException("亲，你的岗位好像不对哟~");
			}

			// 设置岗位信息  存在缓存中
			sysMgrInfo.setSysPostId(sysPostId);
		}

		CacheHelper.setSysMgrInfoCache(sysMgrInfo); // 设置缓存

		SysMgrInfoDTO sysMgrInfoCache = CacheHelper.getSysMgrInfoCache();
		System.out.println("==============> sysMgrInfoCache: " + sysMgrInfoCache);
		addCookie(response, SYS_CODE, System.getProperty(SYS_CODE, "ctg-ae"));

		return new CommonResult(HttpStatus.OK.toString(), "缓存设置成功");
	}

	private void addCookie(HttpServletResponse response, String key, String value) {
		Cookie cookie2 = new Cookie(key, value);
		cookie2.setPath("/");
		response.addCookie(cookie2);
	}

	
	@RequestMapping("/getSysMgrInfo")
	@ResponseBody
	public CommonResult getSysMgrInfo() throws CacheConfigException {
		SysMgrInfoDTO sysMgrInfo = CacheHelper.getSysMgrInfoCache(WebUtils.getCtgUser().getSysUserId()+"");
		return new CommonResult(HttpStatus.OK.toString(), "success", sysMgrInfo);
	}
	
	static {
		PropertiesUtils properties = PropertiesUtils.getInstance(SYS_PROPERTIES);
		String sysCode = properties.get(SYS_CODE);
		System.out.println("sysCode: " + sysCode);
		if (StringUtils.isNotBlank(sysCode))
			System.setProperty(SYS_CODE, sysCode);
	}

}
